package com.lanju.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.lanju.commom.CommonUtils;
import com.lanju.dao.ContractDao;
import com.lanju.dao.HouseDao;
import com.lanju.dao.SMSCaptchaDao;
import com.lanju.dao.UserDao;
import com.lanju.dao.ZuKeContractDao;
import com.lanju.entity.Contract;
import com.lanju.entity.House;
import com.lanju.entity.SMSCaptcha;
import com.lanju.entity.User;
import com.lanju.entity.ZukeContract;
import com.lanju.model.ResultModel;
import com.lanju.service.UserService;
import com.lanju.util.SecurityContext;


@Service
public class UserServiceImpl implements UserService{

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    UserDao userDao;
    
    @Autowired
    SMSCaptchaDao sMSCaptchaDao;
    
    @Autowired
    ContractDao contractDao;
    
    @Autowired
	HouseDao houseDao;
    
    @Autowired
    ZuKeContractDao zuKeContractDao;
    

    /** 新增用户 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel add(User user) {
        User u = userDao.getByPhone(user.getPhone());
        if(u!=null){
            return ResultModel.fail("该手机用户已存在", null);
        }
        user.setUserId(UUID.randomUUID().toString());
        if(user.getPassword()!=null){
        	user.setPassword(CommonUtils.GetMD5Code(user.getPassword()));
        }
        try {
        	userDao.persist(user);
            return ResultModel.success("录入成功", null);
        } catch (Exception e) {
            LOGGER.error("addUser fail",e);
        }
        return ResultModel.fail("录入失败", null);
    }
    
    /** 通过openid新增用户 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel addByOpenid(User user) {
    	Map map=new HashMap<>();
    	map.put("openId", user.getOpenId());
        User u = userDao.getByOpenId(map);
        if(u!=null){
            return ResultModel.fail("该微信用户已存在", null);
        }
        user.setUserId(UUID.randomUUID().toString());
        try {
        	userDao.persist(user);
            return ResultModel.success("新增成功", null);
        } catch (Exception e) {
            LOGGER.error("addUser fail",e);
        }
        return ResultModel.fail("录入失败", null);
    }

    /** 根据id删除用户 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel del(User user) {
    	String userId = user.getUserId();
        User obj = userDao.getById(userId);
        if(obj==null){
            return ResultModel.fail("User不存在", null);
        }
        try {
            userDao.remove(user);;
            return ResultModel.success("删除成功", null);
        } catch (Exception e) {
            LOGGER.error("delUser fail",e);
        }
        return ResultModel.fail("删除失败", null);
    }
    
    /** 根据id修改用户信息 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel edit(User user) {
        User obj = userDao.getById(user.getUserId());
        if(obj==null){
            return ResultModel.fail("User不存在", null);
        }
        User obj2 = userDao.getByPhone(user.getPhone());
        if(obj2!=null && obj2.getUserId()!=user.getUserId()){
            return ResultModel.fail("该手机号的用户已存在，请改为别的手机号码", null);
        }
        try {
            userDao.merge(user);
            return ResultModel.success("编辑成功", null);
        } catch (Exception e) {
            LOGGER.error("editUser fail",e);
        }
        return ResultModel.fail("编辑失败", null);
    }

    /** 根据id获取用户 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public User getById(String id) {
        User obj = userDao.getById(id);
        return obj;
    }
    
    /** 根据手机号码获取用户 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public User getByPhone(Map<String, Object> param) {
    	String phone = (String)param.get("phone");
        User obj = userDao.getByPhone(phone);
        return obj;
    }
    
    /** 根据openId获取用户 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public User getByOpenId(Map<String, Object> param) {
        User obj = userDao.getByOpenId(param);
        return obj;
    }
    
    /** 根据手机号码和密码获取用户 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public User getByPhoneAndPassword(Map<String, Object> param) {
    	String password = (String)param.get("password");
    	password = CommonUtils.GetMD5Code(password);
    	param.put("password", password);
        User user = userDao.getByPhoneAndPassword(param);
        if( user==null || !password.equalsIgnoreCase(user.getPassword())){
        	return null;
        }
        return user;
    }

    /** 分页查询用户 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public Map<String, Object> getList(User user,int pageSize, int offset) {
    	 Map<String, Object> rsMap = new HashMap<String, Object>();
    	 long count = userDao.getListCount(user);
         List<User> list = userDao.getList(user, pageSize, offset);
         rsMap.put("total", count);
         rsMap.put("rows", list);
        return rsMap;
    }
    
    /** 用户注册 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel regist(Map<String,Object> param,HttpServletRequest request) {
    	try {
    		// 判断该手机号是否已被注册
	    	String phone = (String)param.get("phone");
	    	String captcha = (String)param.get("captcha");
	        User user = userDao.getByPhone(phone);
	        if(user!=null){
	            return ResultModel.fail("该手机号码已被注册已存在", null);
	        }
	        
	        // 判断验证码有效性
	        SMSCaptcha sMSCaptcha = sMSCaptchaDao.getByPhoneBy5Min(phone);
	        if(sMSCaptcha==null){
	            return ResultModel.fail("验证码错误", null);
	        }else if( !sMSCaptcha.getCaptcha().toUpperCase().equals(captcha.toUpperCase()) ){
	        	return ResultModel.fail("验证码错误", null);
	        }
	        
	        // 新增用户
	        user = new User();
	        user.setUserId(UUID.randomUUID().toString());
	        user.setPhone(phone);
	        user.setPassword(CommonUtils.GetMD5Code((String)param.get("password")));
	        user.setNickName(phone);
	        user.setStatus(1);
	        user.setHeadImg("/dataResourceImages/household/huanglaoshi.jpg,");
	        String flag=(String)param.get("flag");
	        if(flag!=null && flag.length()>0){
	        	user.setFlag(Integer.parseInt(flag));
	        }
        	userDao.persist(user);
        	
        	//登录
        	Map<String,Object> login_map=new HashMap<>();
        	login_map.put("phone", user.getPhone());
        	login_map.put("password",user.getPassword());
        	login_map.put("flag",String.valueOf(user.getFlag()));
	        User login_user = userDao.getByPhoneAndPassword(login_map);
			System.out.println("登录时找到的user=" + user);
			if (login_user != null) {
				SecurityContext.saveUserToSeesion(login_user, request.getSession());
				SecurityContext.setUser(login_user);
				System.out.println(user.getNickName() + "[" + user.getPhone()
						+ "] has auth success login");
			} 
            return ResultModel.success("注册成功,正在跳转", user);
        } catch (Exception e) {
            LOGGER.error("addUser fail",e);
            return ResultModel.fail("注册失败", null);
        }
      
    }

    /** 找回密码 */
    @Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
    public ResultModel findPassword(Map<String,Object> param) {
        try {
	        String phone = (String)param.get("phone");
	    	String captcha = (String)param.get("captcha");
	    	
	    	// 判断验证码有效性
	        SMSCaptcha sMSCaptcha = sMSCaptchaDao.getByPhoneBy5Min(phone);
	        if(sMSCaptcha==null){
	            return ResultModel.fail("验证码错误", null);
	        }else if( !sMSCaptcha.getCaptcha().toUpperCase().equals(captcha.toUpperCase()) ){
	        	return ResultModel.fail("验证码错误", null);
	        }
	

	        User user = userDao.getByPhone(phone);
	        if(user==null){
	        	return ResultModel.success("找回失败,未获取到当前手机号码用户", null);
	        }else{
	        	user.setPassword(CommonUtils.GetMD5Code((String)param.get("password")));
	        }
            userDao.merge(user);
            return ResultModel.success("修改密码成功", null);
        } catch (Exception e) {
            LOGGER.error("findPassword fail",e);
        }
        return ResultModel.fail("编辑失败", null);
    }
    
    
    /** 获取我的管家 */
    @Override
    @Transactional(value="financialmarketingTM", readOnly=true)
    public ResultModel getMyGuanJia(Map<String, Object> param) {
    	try{
	    	String agreementType = (String)param.get("agreementType");
//	    	String status = (String)param.get("status");
//	    	String userId = (String)param.get("userId");
//	    	Agreement aParam = new Agreement();
//	    	aParam.setAgreementType(agreementType);
//	    	aParam.setStatus(status);
	    	String guanjiaId = null;
	    	String addr = null;
//	    	Agreement agreement = null;
	    	ZukeContract zukeContract =  null;
	    	Contract contract = null;
	    	if("0".equals(agreementType)){	//租客合同  
	    		zukeContract = zuKeContractDao.getContract(param);
	    		addr = zukeContract==null?null:zukeContract.getRenter_addr(); //租房地址   地址
	    		param.put("houseName", addr);
	    		House h = houseDao.getHouseByAddr(param);
	    		guanjiaId = h.getHoldId();
	    	}else{
	    		contract = contractDao.getContract(param);
	    		addr = contract ==null ?null : contract.getHouseAddress();
	    		param.put("houseName", addr);
	    		House h = houseDao.getHouseByAddr(param);
	    		guanjiaId = h.getHoldId();
	    	}
	    	if(guanjiaId ==null){
		    	return ResultModel.success("", null);
	    	}
	    	User user = userDao.getById(guanjiaId);
//	    	HouseHold household=houseHoldDao.getHouseHoldListByPhone(user.getPhone());
	    	Map<String ,Object> resut=new HashMap<>();
	    	resut.put("household", user);
//	    	resut.put("sysdmin", household.getSystemAdmin());
	    	return ResultModel.success("", resut);
        } catch (Exception e) {
            LOGGER.error("getMyGuanJia fail",e);
        }
        return ResultModel.fail("未获取到我的管家", null);
    }

	@Override
	public List<User> getSendMessageUser(Map<String, Object> param) {
		return userDao.getSendMessageUser(param);
	}

	@Override
    @Transactional(value="financialmarketingTM", rollbackFor = Exception.class)
	public Map<String, Object> updateUserInfo(Map<String, Object> map,HttpSession session) {
		Map<String,Object> result = new HashMap<>();
		try {
			User user = userDao.getById(map.get("userId").toString());
			if(user != null ){
				if(!StringUtils.isEmpty(map.get("nickName")))user.setNickName(map.get("nickName").toString());
				if(!StringUtils.isEmpty(map.get("url")))user.setHeadImg(map.get("url").toString());
				userDao.updateUserInfo(user);
				session.setAttribute("userModel", user);
			}
			result.put("success", true);
			result.put("msg", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("msg", "修改失败");
		}
		return result;
	}
    
}
